<template>
	<div>
		<a-card :bordered="false">
			<template #title>
				数据源：<a-select v-model:value="dbsId" :options="dbsList" size="small" @change="getDbTableList(dbsId)"/>
			</template>
			<template #extra>
				<a v-if="dbTableList.length > 0" @click="formRef.onOpen({ dbsId: dbsId })">
					<plus-outlined />
					新增
				</a>
			</template>
			<a-table
				v-if="dbTableList.length > 0"
				:dataSource="dbTableList"
				:columns="columns"
				:scroll="{ y: 600 }"
				:pagination="false"
				bordered
				size="middle"
			>
				<template #bodyCell="{ column, record }">
					<template v-if="column.dataIndex === 'tableName'">
						<a @click="selectTableName(record.tableName, record.tableRemark)">{{ record.tableName }}</a>
					</template>
					<template v-if="column.dataIndex === 'action'">
						<a @click="formRef.onOpen({ ...record, dbsId: dbsId, isEdit: true })"> 修改 </a>
						<a-divider type="vertical" />
						<a-popconfirm title="确定要删除字段吗？" placement="topRight" @confirm="deleteTable(record)">
							<a-button type="link" danger size="small">删除</a-button>
						</a-popconfirm>
					</template>
				</template>
			</a-table>
			<a-empty v-else :image="Empty.PRESENTED_IMAGE_SIMPLE" />
		</a-card>
		<Form ref="formRef" @successful="formSuccessful" />
	</div>
</template>
<script setup>
	import { Empty } from 'ant-design-vue'
	import dmApi from '@/views/plugin/dbs/api/dmApi'
	import Form from './form.vue'
	import tool from '@/utils/tool'

	const emits = defineEmits(['selectTableName'])
	const dbsId = ref('master')
	const columns = ref([
		{
			title: '表名',
			dataIndex: 'tableName',
			key: 'tableName',
			align: 'center'
		},
		{
			title: '注释',
			dataIndex: 'tableRemark',
			key: 'tableRemark',
			align: 'center'
		},
		{
			title: '操作',
			dataIndex: 'action',
			width: 120,
			align: 'center'
		}
	])
	// 数据库表
	const formRef = ref()
	const dbTableList = ref([])
	const dbsList = ref([])
	// 默认加载
	onMounted(() => {
		dmApi.dbInfoList().then((data) => {
			dbsList.value = data.map((item) => {
				return {
					value: item['id'],
					label: item['poolName'] + '-' + tool.dictTypeData('DATABASE_DRIVE_TYPE', item['driverName'])
				}
			})
			// 默认打开第一个
			nextTick(() => {
				if (dbsList.value.length > 0) {
					getDbTableList(dbsList.value[0].value)
				}
			})
		})
	})
	const selectTableName = (value, tableRemark) => {
		emits('selectTableName', value, dbsId.value, tableRemark)
	}
	// 新增编辑成功刷新
	const formSuccessful = () => {
		getDbTableList(dbsId.value)
	}
	// 获取数据库表
	const getDbTableList = (value = dbsId.value) => {
		const param = {
			dbsId: value
		}
		dmApi.tables(param).then((data) => {
			dbTableList.value = data
			// 让列表界面也随动
			selectTableName(data[0].tableName, data[0].tableRemark)
		})
	}
	// 删除表
	const deleteTable = (item) => {
		const param = {
			dbsId: dbsId.value,
			tableName: item.tableName
		}
		dmApi.deleteTable(param).then(() => {
			getDbTableList()
		})
	}
	// 抛出函数
	defineExpose({
		getDbTableList
	})
</script>
